package com.luke.exercise.concurrent;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ProduceConSumerDemo {

    public static void main(String[] args) {
        List<Task> buffer = new ArrayList<Task>(Constants.MAX_BUFFER_SIZE);
        ExecutorService service = Executors.newFixedThreadPool(5);
        for(int i=0 ; i<2 ; i++) {
            service.execute(new Producer(buffer));
        }
        for(int i=0 ; i<3 ; i++) {
            service.execute(new Consumer(buffer));
        }
    }
}

class Constants {
    public static final int MAX_BUFFER_SIZE = 10;
}

class Task {
    private String id;
    
    public Task() {
        id= UUID.randomUUID().toString();
    }
    
    public String toString() {
        return "Task["+ id +"]";
    }
}

class Consumer implements Runnable {

    private List<Task> buffer;
    
    public Consumer(List<Task> buffer) {
        this.buffer = buffer;
    }
    
    public void run() {
        while (true) {
            synchronized (buffer) {
                while (buffer.isEmpty()) {
                    System.out.println("木有库存了");
                    try {
                        buffer.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                Task task = buffer.remove(0);
                buffer.notifyAll();
                System.out.println("Consumer[" + Thread.currentThread() + "] consume "+ task);
            }
        }
    }
}

class Producer implements Runnable {

    private List<Task> buffer;
    
    public Producer(List<Task> list) {
        this.buffer = list;
    }
    public void run() {
        while (true) {
            synchronized (buffer) {
                while (buffer.size() >= Constants.MAX_BUFFER_SIZE) {
                    System.out.println("爆仓库了");
                    try{
                        buffer.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                Task task = new Task();
                buffer.add(task);
                buffer.notifyAll();
                System.out.println("Producer["+ Thread.currentThread() +"] produce "+ task);
            }
        }
    }
    
}